import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout.vue'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { requiresGuest: true }
  },
  {
    // 问卷填写页面 - 不需要登录即可访问
    path: '/answer/:id',
    name: 'SurveyAnswer',
    component: () => import('../views/SurveyAnswer.vue')
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('../views/Home.vue')
      },
      {
        path: 'surveys',
        name: 'Surveys',
        component: () => import('../views/Surveys.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'create',
        name: 'CreateSurvey',
        component: () => import('../views/CreateSurvey.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'edit/:id',
        name: 'EditSurvey',
        component: () => import('../views/Edit.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'results',
        name: 'Results',
        component: () => import('../views/Results.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'results/:id',
        name: 'SurveyResults',
        component: () => import('../views/Results.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'user',
        name: 'User',
        component: () => import('../views/User.vue'),
        meta: { requiresAuth: true }
      }, {
        path: 'manage',
        name: 'Manage',
        component: () => import('../views/UserManage.vue'),
        meta: { requiresAuth: true }
      },
    ]
  },
  // 添加通配符路由
  {
    path: '/:pathMatch(.*)*',
    redirect: '/'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.meta.requiresAuth && !token) {
    // 需要认证但没有token，重定向到登录页
    next({ path: '/login', query: { redirect: to.fullPath } })
  } else if (to.meta.requiresGuest && token) {
    // 游客页面但已登录，重定向到首页
    next('/')
  } else {
    next()
  }
})

export default router